package uc.allapp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ListView;
import cn.onekit.CALLBACK;
import cn.onekit.JSON;
import cn.onekit.android.ACTIVITY;
import co.chuangdian.oflauncher.R;
import uc.allapp.SideBar.OnTouchingLetterChangedListener;

public class AllAppView extends FrameLayout {
	private ListView appListView;
	ViewGroup selectedViewGroup;
	HorizontalScrollView selectedScrollView;
	private SideBar sideBar;
	private SectionAdapter adapter;

	private CharacterParser characterParser;

	public AllAppView(Context context) {
		super(context);
		init();
	}

	public AllAppView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	PackageManager packageManager;

	void init() {
		packageManager = getContext().getPackageManager();
		View.inflate(getContext(), R.layout.uc_allappview, this);
		characterParser = CharacterParser.getInstance();

		sideBar = (SideBar) findViewById(R.id.sidrbar);

		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {

			}
		});

		appListView = (ListView) findViewById(R.id.appListView);
		selectedScrollView = (HorizontalScrollView) findViewById(R.id.selectedScrollView);
		selectedViewGroup = (ViewGroup) findViewById(R.id.selectedViewGroup);
		Map<String, List<ResolveInfo>> allApp = filledData();
		adapter = new SectionAdapter(getContext(), allApp, new CALLBACK<String>() {

			@Override
			public void run(boolean select, String appID) {
				if (select) {
					selectApp(appID);
					selectAppDone();
				} else {
					deselectApp(appID);
				}
			}

		});
		appListView.setAdapter(adapter);
	}

	JSONArray appIDs = new JSONArray();

	public void setData(final JSONArray appIDs) {
		this.appIDs = new JSONArray();
		//
		selectedViewGroup.removeAllViews();
		for (int i=0;i<appIDs.length();i++) {
			selectApp(appIDs.optString(i));
		}
		selectAppDone();
	}

	void selectApp(String appID) {
		appIDs.put(appID);
		PackageInfo app;
		final int size = ACTIVITY.dp2px(50);
		ImageView iconView = new ImageView(getContext());
		iconView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String deleteID = (String) v.getTag();
				deselectApp(deleteID);
			}

		});
		iconView.setLayoutParams(new LayoutParams(size, size));
		try {
			iconView.setTag(appID);
			app = packageManager.getPackageInfo(appID, 0);
			Drawable icon = app.applicationInfo.loadIcon(packageManager);
			iconView.setImageDrawable(icon);
			selectedViewGroup.addView(iconView);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	void selectAppDone() {
		adapter.setData(appIDs);
		adapter.notifyDataSetChanged();
		new Handler().post(new Runnable() {
			@Override
			public void run() {
				selectedScrollView.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
			}
		});
	}

	void deselectApp(String appID) {
		appIDs = JSON.remove(appIDs,appID);
		adapter.setData(appIDs);
		adapter.notifyDataSetChanged();
		//
		for (int i = 0; i < selectedViewGroup.getChildCount(); i++) {
			ImageView iconView = (ImageView) selectedViewGroup.getChildAt(i);
			if (iconView.getTag().equals(appID)) {
				selectedViewGroup.removeView(iconView);
				break;
			}
		}
	}

	public JSONArray getData() {
		return appIDs;
	}

	/**
	 * ΪListView�������
	 * 
	 * @param date
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	private Map<String, List<ResolveInfo>> filledData() {
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		PackageManager packageManager = getContext().getPackageManager();
		List<ResolveInfo> allApp = packageManager.queryIntentActivities(mainIntent, 0);
		Map<String, List<ResolveInfo>> mSortList = new HashMap<String, List<ResolveInfo>>();

		for (ResolveInfo app : allApp) {
			String name = (String) packageManager.getApplicationLabel(app.activityInfo.applicationInfo);
			String pinyin = characterParser.getSelling(name);
			if (pinyin == null || pinyin == "") {
				continue;
			}
			String sortString = pinyin.substring(0, 1).toUpperCase();
			String index;
			if (sortString.matches("[A-Z]")) {
				index = sortString.toUpperCase();
			} else {
				index = "#";
			}
			List<ResolveInfo> apps;
			if (mSortList.containsKey(index)) {
				apps = mSortList.get(index);
			} else {
				apps = new ArrayList<ResolveInfo>();
			}
			apps.add(app);
			mSortList.put(index, apps);
		}
		return mSortList;
	}

}
